package com.dtzhejiang.social.supervision.risk.engine.core.task.tasklet;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dtzhejiang.social.supervision.risk.engine.common.domain.po.SpiderHospitalEntity;
import com.dtzhejiang.social.supervision.risk.engine.common.domain.po.SuperviseObjectInfoEntity;
import com.dtzhejiang.social.supervision.risk.engine.common.util.LatitudeUtils;
import com.dtzhejiang.social.supervision.risk.engine.core.mapper.SpiderHospitalMapper;
import com.dtzhejiang.social.supervision.risk.engine.core.mapper.SuperviseObjectInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: yuweiwen
 * Date: 2020/1/13 10:19
 * Content:
 */
@Component
public class LongTaTask {

    private static Logger logger = LoggerFactory.getLogger(LongTaTask.class);

    @Autowired
    private SuperviseObjectInfoMapper superviseObjectInfoMapper;

    @Autowired
    private SpiderHospitalMapper spiderHospitalMapper;

    //每天凌晨三点执行一次
    private static final String DAY_ZERO_THREE = "0 0 3 * * ?";

    /**
     * 获取医疗机构对象经纬度
     */
    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 2))
    public void getLaTaForShop() {

        List<SpiderHospitalEntity> spiderHospitalEntityList;
        QueryWrapper<SpiderHospitalEntity> wrapper = new QueryWrapper<>();
        QueryWrapper<SpiderHospitalEntity> queryWrapper = wrapper.select("city,name,id,address").isNull("latitude");

        spiderHospitalEntityList = spiderHospitalMapper.selectList(queryWrapper);
        if (spiderHospitalEntityList.size() > 0) {
            if (spiderHospitalEntityList.size() < 100) {
                hospitalLata(spiderHospitalEntityList);
            } else {
                int len = 100;
                int size = spiderHospitalEntityList.size();
                int count = (size + len - 1) / len;
                for (int i = 0; i < count; i++) {
                    List<SpiderHospitalEntity> subList = spiderHospitalEntityList.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
                    hospitalLata(subList);
                }
            }
        }
    }

    private <U> Boolean hospitalLata(List<SpiderHospitalEntity> spiderHospitalEntityList) {
        List<SpiderHospitalEntity> list = new ArrayList<>(spiderHospitalEntityList.size());
        try {
            Map map = null;
            for (int i = 0; i < spiderHospitalEntityList.size(); i++) {
                LatitudeUtils lu = new LatitudeUtils();
                String address = spiderHospitalEntityList.get(i).getAddress();
                String city=spiderHospitalEntityList.get(i).getCity();
                if(StringUtils.isBlank(address)){
                    if(StringUtils.isNotBlank(spiderHospitalEntityList.get(i).getName())){
                        address= spiderHospitalEntityList.get(i).getName();
                    }else{
                        continue;
                    }

                }
                if(!city.contains("市")){
                    city=city+"市";
                }
//                map = lu.getGeocoderLatitude(address,city);
                //更新经纬度到表中
                if (map != null) {
                    if (map.get("lng") != null && map.get("lat") != null) {
                        spiderHospitalEntityList.get(i).setLongitude(new BigDecimal((String) map.get("lng")));
                        spiderHospitalEntityList.get(i).setLatitude(new BigDecimal((String) map.get("lat")));
                        logger.info("id:{} 经度为：{} 纬度为：{}", spiderHospitalEntityList.get(i).getId(), spiderHospitalEntityList.get(i).getLongitude(), spiderHospitalEntityList.get(i).getLatitude());
                        list.add(spiderHospitalEntityList.get(i));

                    }
                }
            }
            if (list.size() > 0) {
//                spiderHospitalMapper.updateDataList(list);
                logger.info("更新数量为：{}", list.size());
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    /**
     * 获取监管对象经纬度
     */
    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 2))
    public void getLaTaForSuperviseObjectInfo() {

        List<SuperviseObjectInfoEntity> superviseObjectInfoEntityList;

        QueryWrapper<SuperviseObjectInfoEntity> wrapper = new QueryWrapper<>();
        QueryWrapper<SuperviseObjectInfoEntity> queryWrapper = wrapper.select("object_name,id,address,region_name").isNull("latitude");

        superviseObjectInfoEntityList = superviseObjectInfoMapper.selectList(queryWrapper);
        if (superviseObjectInfoEntityList.size() > 0) {
            if (superviseObjectInfoEntityList.size() < 1000) {
                superviseObjectLata(superviseObjectInfoEntityList);
            } else {
                int len = 1000;
                int size = superviseObjectInfoEntityList.size();
                int count = (size + len - 1) / len;
                for (int i = 0; i < count; i++) {
                    List<SuperviseObjectInfoEntity> subList = superviseObjectInfoEntityList.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
                    superviseObjectLata(subList);
                }
            }
        }
    }


    private <U> Boolean superviseObjectLata(List<SuperviseObjectInfoEntity> superviseObjectInfoEntityList) {
        List<SuperviseObjectInfoEntity> list = new ArrayList<>(superviseObjectInfoEntityList.size());
        try {
            Map map = null;
            for (int i = 0; i < superviseObjectInfoEntityList.size(); i++) {
                LatitudeUtils lu = new LatitudeUtils();
                String address = superviseObjectInfoEntityList.get(i).getAddress();
                String regionName=superviseObjectInfoEntityList.get(i).getRegionName();
                if(StringUtils.isBlank(address)){
                    if(StringUtils.isNotBlank(superviseObjectInfoEntityList.get(i).getObjectName())){
                        address= superviseObjectInfoEntityList.get(i).getObjectName();
                    }else{
                        continue;
                    }

                }
                if(StringUtils.isNotBlank(regionName)&& regionName.length()>=3){
                    regionName=regionName.substring(0,3);
                }else{
                    regionName="";
                }
                logger.info("城市名为：{}",regionName);
//                map = lu.getGeocoderLatitude(address,regionName);
                //更新经纬度到表中
                if (map != null) {
                    if (map.get("lng") != null && map.get("lat") != null) {
                        superviseObjectInfoEntityList.get(i).setLongitude(new BigDecimal((String) map.get("lng")));
                        superviseObjectInfoEntityList.get(i).setLatitude(new BigDecimal((String) map.get("lat")));
                        logger.info("id:{} 经度为：{} 纬度为：{}", superviseObjectInfoEntityList.get(i).getId(), superviseObjectInfoEntityList.get(i).getLongitude(), superviseObjectInfoEntityList.get(i).getLatitude());
                        list.add(superviseObjectInfoEntityList.get(i));
                    }
                }
            }
            if (list.size() > 0) {
                superviseObjectInfoMapper.updateDataList(list);
                logger.info("更新数量为：{}", list.size());
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }


}
